package com.peanut.baby.mvp.livedetail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.http.ApiException;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.livedetail.detail.LiveDetailFragment;
import com.peanut.baby.mvp.livedetail.group.LiveDetailGroupFragment;
import com.peanut.baby.mvp.liveroom.AppVoicePlayer;
import com.peanut.baby.mvp.liveroom.LiveRoomActivity;
import com.peanut.baby.mvp.liveroom.RoomLectureFragment;
import com.peanut.baby.util.ShareUtil;
import com.peanut.baby.widget.CustomViewPager;
import com.peanut.devlibrary.adapter.FragmentTabAdapter;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/7/17.
 */

public class LiveDetailActivity extends BaseMvpActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener,
        TitleLayout.OnTitleClickListener, LiveDetailContract.View {
    private static final String TAG = LiveDetailActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.live_detail_image)
    ImageView image;
    @BindView(R.id.live_detail_viewpager)
    CustomViewPager viewpager;
    @BindView(R.id.roomtab)
    RadioGroup radioGroup;

    private LiveDetailContract.Presenter presenter;
    int liveId;
    int from;
    LiveRoom liveRoom;
    ArrayList<Fragment> fragments;
    FragmentTabAdapter adapter;

    public static void start(Context ctx, int id) {
        ctx.startActivity(new Intent(ctx, LiveDetailActivity.class).putExtra("id", id));
    }

    public static void start(Context ctx, int id,int from) {
        ctx.startActivity(new Intent(ctx, LiveDetailActivity.class).putExtra("id", id).putExtra("from",from));
    }

    public static void start(Context ctx, LiveRoom room) {
        ctx.startActivity(new Intent(ctx, LiveDetailActivity.class).putExtra("room", room));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == AppConfig.RequestResult.REQUEST_CODE_LOGIN) {
            requestRoomDetail();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_detail);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("id")) {
            liveId = getIntent().getIntExtra("id", -1);
        }

        if (getIntent().hasExtra("room")) {
            liveRoom = (LiveRoom) getIntent().getSerializableExtra("room");
            liveId = liveRoom.roomId;
        }
        if(getIntent().hasExtra("from")){
            from = getIntent().getIntExtra("from", 0);
        }
        presenter = new LiveDetailPresenter(this, this);
        initView();
        bindDefaultDataOrRequest();
    }


    private void initView() {
        title.setOnTitleClickedListener(this);
        title.setTitle("直播课程");
        title.setTitleRightTextDrawable("", R.drawable.icon_share);
        title.setTitleRightVisibility(true);

        radioGroup.setOnCheckedChangeListener(this);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) image.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 9 / 16;
        image.setLayoutParams(params);
    }

    private void bindDefaultDataOrRequest() {
        if (liveRoom != null) {
            bindData();
        } else {
            requestRoomDetail();
        }
    }
    public void requestData(long id){
        showProgressDialog("请稍候...", false);
        presenter.getRoomDetail(id + "");
    }

    private void requestRoomDetail() {
        showProgressDialog("请稍候...", false);
        presenter.getRoomDetail(liveId + "");
    }

    private void bindData() {
        ImageLoader.getInstance().loadImageView(LiveDetailActivity.this, liveRoom.roomImageUrl, image);
        viewpager.setOnPageChangeListener(this);
        fragments = new ArrayList<>();
        fragments.add(LiveDetailFragment.newInstance(liveRoom));
        fragments.add(LiveDetailGroupFragment.newInstance(liveRoom));
        adapter = new FragmentTabAdapter(getSupportFragmentManager(), fragments);
        viewpager.setAdapter(adapter);
        if(from==1){
            setCurrent(1);
        }
    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {
        new BaseDialog().showShareDialog(LiveDetailActivity.this, new BaseDialog.OnShareItemSelected() {
            @Override
            public void onShareItemSelected(int item) {
                String platName = "";
                if (item == BaseDialog.OnShareItemSelected.TYPE_MOMENT) {
                    platName = WechatMoments.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN) {
                    platName = Wechat.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIBO) {
                    platName = SinaWeibo.NAME;
                } else if (item == BaseDialog.OnShareItemSelected.TYPE_QQ) {
                    platName = QQ.NAME;
                }
                if (StringUtil.isNullOrEmpty(platName)) {
                    return;
                }
                if (liveRoom == null) {
                    return;
                }
                ShareUtil.getInstance().shareLive(liveRoom, platName, new ShareUtil.IShareCallback() {
                    @Override
                    public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                        showToast(isSuccess ? "分享成功" : failReason);
                        if (isSuccess && InitManager.getInstance().getUser() != null) {
                            TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), com.peanut.devlibrary.util.TimeUtil.getCurrentDate());
                            record.shareLiveCount++;
                            if (record.shareLiveCount > 1) {
                                record.shareLiveCount = 1;
                            } else {
                                presenter.sharePoint(liveRoom.roomId + "");
                            }
                            DBManager.getInstance().updateTaskRecord(record);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onGetRoomDetailSuccess(LiveRoom room) {
        dismissProgressDialog();
        this.liveRoom = room;
        bindData();
    }

    @Override
    public void onRequestFailed(String code, String reason) {
        dismissProgressDialog();
        if (!ApiException.isApiException(code)) {
            showToast(reason);
        }

    }

    @Override
    public void onJoinSuccess() {
        dismissProgressDialog();
        showToast("报名成功");
        LiveRoomActivity.start(this, liveRoom);
    }

    @Override
    public void onSharePointSuccess(String tips) {
        showToast(tips);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.roominfo:
                setCurrent(0);
                break;
            case R.id.xiliekelist:
                setCurrent(1);
                break;
        }
    }

    private void setCurrent(int currentIndex) {
        if(currentIndex == 0){
            ImageLoader.getInstance().loadImageView(LiveDetailActivity.this, liveRoom.roomImageUrl, image);
        } else {
            if(liveRoom.liveGroup!=null && liveRoom.liveGroup.pic!=null)
                ImageLoader.getInstance().loadImageView(LiveDetailActivity.this, liveRoom.liveGroup.pic, image);
        }
        RadioButton radioButton = (RadioButton) radioGroup.getChildAt(currentIndex);
        if (!radioButton.isChecked()) {
            radioButton.setChecked(true);
        }
        if (viewpager.getCurrentItem() != currentIndex) {
            viewpager.setCurrentItem(currentIndex);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurrent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    @Override
    protected void onPause() {
        super.onPause();
        if (AppVoicePlayer.getInstance().isPlaying()) {
            Log.d(RoomLectureFragment.class.getSimpleName(),"room on Pause");
            AppVoicePlayer.getInstance().releasePlayer();
        }
    }
    @Override
    protected void onDestroy() {
        AppVoicePlayer.getInstance().onDestory();
        super.onDestroy();
    }
}
